package com.qipay.api.callback.controller.v1;

import com.qipay.baas.model.Order;
import com.qipay.order.service.OrderService;
import com.qipay.sp.SpConfigService;
import com.qipay.utils.MD5Util;
import com.qipay.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/callback/v1/xinyu")
public class XinyuCallbackController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
	OrderService orderService;

    @Autowired
	SpConfigService spConfigService;

    @RequestMapping(value = "/wx")
    private String unionCreate(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, String> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        if(params!=null&&"1".equals(params.get("status"))){
            String tradeNo = params.get("transId");
            Order order = orderService.getByTradeNo(tradeNo);
            if(order==null) {
                logger.info("回调失败：查无此订单="+tradeNo);
                return "fail";
            }
            Map<String, Object> keyValues = spConfigService.getKeyValues(order.getSpId());
            String key = keyValues.get("key").toString();
            String fromSign = params.get("sign");
            Map<String, Object> paramso = new HashMap<>();
            for(Map.Entry<String, String> entry:params.entrySet()){
                if(!"null".equals(entry.getValue()))paramso.put(entry.getKey(),entry.getValue());
            }
            String mySign =  MD5Util.getSign(paramso,key);
            if(fromSign.equals(mySign)){
                orderService.setOrderSuccess(order.getId(), null);
                return "success";
            }else {
                logger.info("回调失败：签名sign不一致，tradeNo="+tradeNo);
            }
        }
        return "fail";
    }

}
